<?php

namespace App\Repositories;

use Exception;
use App\Models\Attendance;
use App\Exceptions\GeneralException;
use Illuminate\Database\Eloquent\Model;

/**
 * Date: 17/04/2018
 * @author George
 * @package App\Repositories
 */
class AttendanceRepository
{
	/**
	 * 定义模型
	 *
	 * Date: 16/04/2018
	 * @author George
	 * @return mixed|string
	 */
	public function model()
	{
		return Attendance::class;
	}

	/**
	 * 用户打卡
	 *
	 * Date: 17/04/2018
	 * @author George
	 * @param array $attributes
	 * @return $this|Model|mixed
	 */
	public function createOrUpdate(array $attributes)
	{
		$attendance = array_pull($attributes, 'attendance');
		if ($attendance instanceof Attendance) {
			$attendance->update($attributes);
		} else {
			$attendance = Attendance::create($attributes);
		}
		return $attendance;
	}

	/**
	 * 根据公司获取考勤数据
	 *
	 * Date: 17/04/2018
	 * @author George
	 * @param bool $start
	 * @param bool $end
	 * @param bool $type
	 * @param bool $project_id
	 * @param $company_id
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	public function all($start = false, $end = false, $type = false, $project_id = false, $company_id = false)
	{
		$query = Attendance::query()->with('user:id,name', 'genre:id,name', 'project:id,name');

		if ($start && $end) {
			$query->whereBetween('date', [$start, $end]);
		}

		if ($type) {
			$query->where('type', $type);
		}

		if ($project_id) {
			$query->where('project_id', $project_id);
		}

		if ($company_id) {
			$query->where('company_id', $company_id);
		}

		return $query;
	}

	/**
	 * 根据用户ID获取某天考勤记录
	 *
	 * Date: 17/04/2018
	 * @author George
	 * @param $user_id
	 * @param bool $date
	 * @return Attendance|Model|static
	 */
	public function getByUser($user_id, $date = false)
	{
		return Attendance::query()
			->where('user_id', $user_id)
			->whereDate('checkin_time', $date ?: date('Y-m-d'))
			->first();
	}

	/**
	 * 保存用户考勤记录
	 *
	 * Date: 16/04/2018
	 * @author George
	 * @param array $attributes
	 * @return Attendance|Model
	 * @throws GeneralException
	 * @throws \Throwable
	 */
	public function store(array $attributes)
	{
		$attendance = $this->serialization($attributes);
		$attendance->saveOrFail();
		return $attendance;
	}

	/**
	 * 序列化考勤数据
	 *
	 * Date: 16/04/2018
	 * @author George
	 * @param array $attributes
	 * @return Attendance|Model
	 * @throws GeneralException
	 */
	protected function serialization(array $attributes)
	{
		$attendance = new Attendance();
		try {
			$attributes->user_id = $attributes['user_id'];
			$attributes->conpany_id = $attributes['user_id'];
			$attributes->project_id = $attributes['project_id'];
			$attributes->schedule_id = $attributes['schedule_id'];
			$attributes->date = date('Y-m-d');
			$attributes->longitude = $attributes['longitude'];
			$attributes->latitude = $attributes['latitude'];
		} catch (Exception $exception) {
			throw new GeneralException('参数有误无法序列化模型', 500);
		}
		return $attendance;
	}

}
